﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增供应商</title>
    <!-- 引入 Element Plus CSS -->
    <!-- 引入 Vue 和 Element Plus JS -->
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            /* 背景板样式 */
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .upload-area {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form label-width="120px">
                <!-- 第一行：客户编码、客户名称 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="供应商编码" required class="form-item">
                            <el-input placeholder="自动获取系统编号" v-model="formData.supplier_code" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商名称" required class="form-item">
                            <el-input v-model="formData.supplier_name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：所属行业、客户来源 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属行业" class="form-item">
                            <!-- v-model 绑定表单中“所属行业”的选中值 -->
                            <el-select v-model="formData.indInd" placeholder="请选择">
                                <!-- 循环渲染从后端获取的字典选项 -->
                                <el-option v-for="item in industryOptions"
                                           :key="item.value"
                                           :label="item.dictLabel"
                                           :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商分类" class="form-item">
                            <!-- v-model 绑定表单中“供应商分类”的选中值 -->
                            <el-select v-model="formData.supplier_classification" placeholder="请选择">
                                <!-- 循环渲染从后端获取的字典选项 -->
                                <el-option v-for="item in SuppOptions"
                                           :key="item.value"
                                           :label="item.dictLabel"
                                           :value="item.dictValue"></el-option>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：联系人、联系电话 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系人" class="form-item">
                            <el-input v-model="formData.contact_person" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" class="form-item">
                            <el-input v-model="formData.contact_phone_number" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第四行：电子邮箱、销售部门 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="电子邮箱" class="form-item">
                            <el-input v-model="formData.email_address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="进货部门" class="form-item" readonly>
                            <el-select placeholder="请选择">
                                <el-option label="销售一部" value="销售一部"></el-option>
                                <el-option label="销售二部" value="销售二部"></el-option>
                                <el-option label="销售三部" value="销售三部"></el-option>
                                <el-option label="大客户部" value="大客户部"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第五行：销售负责人、状态 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="进货负责人" class="form-item">
                            <el-select placeholder="请选择">
                                <el-option label="张三" value="张三"></el-option>
                                <el-option label="李四" value="李四"></el-option>
                                <el-option label="王五" value="王五"></el-option>
                                <el-option label="赵六" value="赵六"></el-option>
                                <el-option label="钱七" value="钱七"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" class="form-item">
                            <el-radio v-model="formData.status" label=1>启用</el-radio>
                            <el-radio v-model="formData.status" label=2>停用</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第六行：客户地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="供应商地址" class="form-item">
                            <el-input v-model="formData.suppliers_address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第七行：备注 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="formData.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 财务信息 -->
        <div class="form-group">
            <h3>财务信息</h3>
            <el-form label-width="120px">
                <!-- 第一行：账户名称、纳税人识别号 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="账户名称" class="form-item">
                            <el-input v-model="formData.account_name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" class="form-item">
                            <el-input v-model="formData.taxid" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：银行账户、开户银行 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="银行账户" class="form-item">
                            <el-input v-model="formData.bank_account" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" class="form-item">
                            <el-input v-model="formData.opening_bank" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：开户行地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="开户行地址" class="form-item">
                            <el-input v-model="formData.bkaddr" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 上传附件 -->
        <div class="form-group">
            <h3>上传附件</h3>
            <div class="upload-area">
                <el-upload action="/api/Supplier/UploadFile"
                           :file-list.sync="fileList"
                           :on-success="handleUploadSuccess"
                           :before-upload="beforeUpload"
                           :limit="3">
                    <el-button type="primary">上传</el-button>
                </el-upload>
                <div class="tip">您可以上传 doc、pdf、rar 等格式的文件，单个文件上传最大 200MB。</div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button type="primary" v-on:click="update">修改</el-button>
        </div>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted } = Vue;
        const app = createApp({
            setup() {
                const fileList = ref([]);
                const industryOptions = ref([]);
                const SuppOptions = ref([]);

                const formData = reactive({
                    supplier_code: '', // 供应商编码（统一字段名）
                    indInd: '',
                    supplier_classification: '',
                    supplier_name: '',
                    contact_person: '',
                    contact_phone_number: '',
                    email_address: '',
                    purchasing_department_id: 1,
                    purchasing_manager_id: 1,
                    suppliers_address: '',
                    account_name: '',
                    taxid: '',
                    bank_account: '',
                    opening_bank: '',
                    bkaddr: '',
                    status: '1',
                    note: '',
                    create_by: 'admin',
                    annex_code: ''
                });

                // 1. 获取URL参数的方法
                const getUrlParam = (paramName) => {
                    const params = new URLSearchParams(window.location.search);
                    return params.get(paramName);
                };

                // 2. 获取行业字典
                const getIndustryDict = async () => {
                    try {
                        // 调用后端接口：/api/Dict/datas/Industry（DictTypeCode 为 Industry）
                        const response = await axios.get('/api/Dict/datas/Industry');
                        console.log(response.data)
                        // 格式化后端返回的字典数据（映射为 Select 组件需要的 label/value 格式）
                        industryOptions.value = response.data;
                        console.log(industryOptions.value)
                    } catch (error) {
                        console.error('获取所属行业字典失败：', error);
                        ElementPlus.ElMessage.error('获取所属行业数据失败，请稍后再试'); // 错误提示
                    }
                };
                // 3. 获取供应商分类字典
                const getSupplierClassificationDict = async () => {
                    try {
                      // 调用后端接口：/api/Dict/datas/Industry（DictTypeCode 为 Industry）
                      const response = await axios.get('/api/Dict/datas/SupplierClassification');
                      console.log(response.data)
                      // 格式化后端返回的字典数据（映射为 Select 组件需要的 label/value 格式）
                      SuppOptions.value = response.data;
                      console.log(SuppOptions.value)
                    } catch (error) {
                      console.error('获取供应商分类字典失败：', error);
                      ElementPlus.ElMessage.error('获取供应商分类数据失败，请稍后再试'); // 错误提示
                    }
                };

                // 4. 页面挂载时：获取字典+URL参数
                onMounted(async () => {
                    // 1. 先加载字典（不依赖参数，可并行）
                    await Promise.all([
                        getIndustryDict(),
                        getSupplierClassificationDict()
                    ]);


                    // 提取URL中的供应商编号并赋值
                    const supplierCode = getUrlParam('code');
                    if (supplierCode) {
                        formData.supplier_code = supplierCode;
                        await getSupplierDetail();
                    }else{
                        ElementPlus.ElMessage.error('未获取到供应商编号');
                    }
                });


                 // 供应商行业字典回显（根据DictValue获取DictLabel）
                const getSupplierClassificationDictValue = async (value) => {
                    try {
                        // 调用正确的接口：/api/Dict/label，参数为dictTypeCode和dictValue
                        const response = await axios.get(`/api/Dict/label?dictTypeCode=Industry&dictValue=${value}`);
                        console.log('供应商行业标签:', response.data); // 打印结果
                        return response.data; // 返回字典标签（DictLabel）
                    } catch (error) {
                        console.error('获取供应商行业标签失败：', error);
                        ElementPlus.ElMessage.error('获取供应商行业标签失败，请稍后再试');
                        return ''; // 出错时返回空字符串
                    }
                };

                // 供应商行业字典回显（根据DictValue获取DictLabel）
                const getIndustryDictValue = async (value) => {
                    try {
                        // 调用正确的接口：/api/Dict/label，参数为dictTypeCode和dictValue
                        const response = await axios.get(`/api/Dict/label?dictTypeCode=SupplierClassification&dictValue=${value}`);
                        console.log('供应商行业标签:', response.data); // 打印结果
                        return response.data; // 返回字典标签（DictLabel）
                    } catch (error) {
                        console.error('获取供应商行业标签失败：', error);
                        ElementPlus.ElMessage.error('获取供应商行业标签失败，请稍后再试');
                        return ''; // 出错时返回空字符串
                    }
                };


                //  加载供应商详情
                const getSupplierDetail = async () => {
                    const code = formData.supplier_code

                    try {
                        console.log(code);
                        // 调用后端详情接口
                        const res = await axios.get(`/api/Supplier/GetSupplierDetail?code=${code}`);
                        console.log(res.data);
                        res.data.data.indInd = await getSupplierClassificationDictValue(res.data.data.indInd)
                        res.data.data.supplier_classification = await getIndustryDictValue(res.data.data.supplier_classification)
                        

                        if (res.data.success) {
                            // 填充表单数据
                            Object.assign(formData, res.data.data);
                            // 加载附件列表（如果有）
                            if (formData.annex_code) {
                                await loadAttachments(formData.annex_code);
                            }
                        } else {
                            ElementPlus.ElMessage.error(res.data.message);
                        }
                    } catch (error) {
                        console.error('加载详情失败：', error);
                        ElementPlus.ElMessage.error('加载详情失败，请重试');
                    }
                };

                // 加载附件列表（新增函数）
                const loadAttachments = async (annexCode) => {
                    try {
                        // 调用后端接口：根据annex_code查询附件
                        const res = await axios.get(`/api/Supplier/GetAttachments?annexCode=${annexCode}`);
                        if (res.data.success) {
                            // 格式化数据为el-upload所需的fileList结构
                            fileList.value = res.data.data.map(file => ({
                                name: file.fileName, // 文件名
                                url: file.fileUrl,   // 文件访问路径（需后端返回可访问的URL）
                                uid: file.id         // 附件唯一标识
                            }));
                        } else {
                            ElementPlus.ElMessage.error(res.data.message);
                        }
                    } catch (error) {
                        console.error('加载附件失败：', error);
                        ElementPlus.ElMessage.error('加载附件失败，请重试');
                    }
                };

                //添加
                const update = async () => {
                    try {
                        // 1. 创建FormData对象（用于提交表单+文件）
                        const formData2 = new FormData();

                        // 2. 添加表单字段（与后端接收模型字段对应）
                        formData2.append("supplier_code", formData.supplier_code);
                        formData2.append("supplier_name", formData.supplier_name);
                        formData2.append("indInd", formData.indInd); // 所属行业（已修正字段名）
                        formData2.append("supplier_classification", formData.supplier_classification);
                        formData2.append("contact_person", formData.contact_person);
                        formData2.append("contact_phone_number", formData.contact_phone_number);
                        formData2.append("email_address", formData.email_address);
                        formData2.append("purchasing_department_id", formData.purchasing_department_id);
                        formData2.append("purchasing_manager_id", formData.purchasing_manager_id);
                        formData2.append("suppliers_address", formData.suppliers_address);
                        formData2.append("account_name", formData.account_name);
                        formData2.append("taxid", formData.taxid);
                        formData2.append("bank_account", formData.bank_account);
                        formData2.append("opening_bank", formData.opening_bank);
                        formData2.append("bkaddr", formData.bkaddr);
                        formData2.append("status", formData.status);
                        formData2.append("note", formData.note);
                        formData2.append("create_by", formData.create_by);
                        formData2.append("annex_code", formData.annex_code); // 关键：传递附件编号


                        // 4. 提交请求（ contentType: false 必加，让浏览器自动处理FormData格式）
                        const response = await axios.post("/api/Supplier/UpdateSupplier", formData2, {
                            headers: { "Content-Type": "multipart/form-data" }
                        });

                        // 5. 处理响应
                        if (response.data.success) {
                            ElementPlus.ElMessage.success("修改供应商成功");
                            goBack(); // 返回列表页
                        } else {
                            ElementPlus.ElMessage.error("修改失败：" + response.data.message);
                        }
                    } catch (error) {
                      console.error("修改失败失败：", error);
                      ElementPlus.ElMessage.error("网络错误，请稍后再试");
                    }
                };


                // 其他方法（save、goBack等，不变）
                const goBack = () => { window.history.back(); };
                const beforeUpload = (file) => { /* ... */ };
                const handleUploadSuccess = (response) => { /* ... */ };

                return {
                    fileList,
                    industryOptions,
                    SuppOptions,
                    formData,
                    goBack,
                    beforeUpload,
                    handleUploadSuccess,
                    update
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>

</html>